// filepath: e:\BaiduSyncdisk\课业文件\DSAA5024数据探索与可视化\homework\project\mv_bike\src\context\TimeContext.tsx
'use client';

import React, { createContext, useState, useEffect, useRef, ReactNode } from 'react';

// 定义时间范围
export const SIMULATION_START_TIME = new Date('2021-05-02T00:00:00Z');
export const SIMULATION_END_TIME = new Date('2021-05-15T00:00:00Z');

// 定义 Context 中提供的数据类型
interface TimeContextType {
  currentTime: Date;
  setCurrentTime: (date: Date) => void;
  isPlaying: boolean;
  setIsPlaying: (playing: boolean) => void;
}

// 创建 Context
export const TimeContext = createContext<TimeContextType | undefined>(undefined);

// 创建一个 Provider 组件，它将包含所有状态管理的逻辑
export const TimeProvider = ({ children }: { children: ReactNode }) => {
  const [currentTime, setCurrentTime] = useState(SIMULATION_START_TIME);
  const [isPlaying, setIsPlaying] = useState(false);
  const intervalRef = useRef<NodeJS.Timeout | null>(null);

  useEffect(() => {
    if (isPlaying) {
      // 如果是播放状态，则设置一个定时器
      intervalRef.current = setInterval(() => {
        setCurrentTime(prevTime => {
          const newTime = new Date(prevTime.getTime() + 30 * 60 * 1000); // 增加30分钟
          if (newTime >= SIMULATION_END_TIME) {
            setIsPlaying(false); // 到达终点时自动停止
            return SIMULATION_END_TIME;
          }
          return newTime;
        });
      }, 1000); // 每 5 秒钟更新一次时间
    } else {
      // 如果不是播放状态，则清除定时器
      if (intervalRef.current) {
        clearInterval(intervalRef.current);
      }
    }

    // 组件卸载时清除定时器，防止内存泄漏
    return () => {
      if (intervalRef.current) {
        clearInterval(intervalRef.current);
      }
    };
  }, [isPlaying]); // 这个 effect 只在 isPlaying 状态改变时运行

  const value = { currentTime, setCurrentTime, isPlaying, setIsPlaying };

  return <TimeContext.Provider value={value}>{children}</TimeContext.Provider>;
};